package com.linkoog.devtools.code_generator.template.render.engine.velocity.directive;

import com.linkoog.devtools.code_generator.template.render.engine.velocity.Placeholder;
import org.apache.commons.lang3.StringUtils;
import org.apache.velocity.context.InternalContextAdapter;
import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.runtime.directive.Directive;
import org.apache.velocity.runtime.parser.node.Node;

import java.io.IOException;
import java.io.Writer;

/**
 * 获取package路径
 */
public class Package extends Directive {
    @Override
    public String getName() {
        return "Package";
    }

    @Override
    public int getType() {
        return LINE;
    }

    @Override
    public boolean render(InternalContextAdapter context, Writer writer, Node node) throws IOException, ResourceNotFoundException, ParseErrorException, MethodInvocationException {
        String basePackage = (String) node.jjtGetChild(0).value(context);
        String suffix = (String) node.jjtGetChild(1).value(context);

        // 解决引号下使用指令，占位符不解析问题
        suffix = Placeholder.resolvePlaceholders(suffix, context);
        if (StringUtils.isBlank(basePackage)){
            writer.write(suffix);
            return true;
        } else {
            writer.write(basePackage + "." + suffix);
            return true;
        }
    }
}
